<template>
  <div class="container">
    <h1>家居管理系统</h1>
    
    <!-- 添加按钮 -->
    <button class="add-btn" @click="showDialog">添加家居</button>
    
    <!-- 家居列表表格 -->
    <table class="furn-table">
      <thead>
        <tr>
          <th>家居名称</th>
          <th>厂商</th>
          <th @click="sortBy('price')">价格 ▲</th>
          <th @click="sortBy('sales')">销量 ▲</th>
          <th>库存</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in furnList" :key="item.id">
          <td>{{ item.name }}</td>
          <td>{{ item.maker }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.sales }}</td>
          <td>{{ item.stock }}</td>
          <td>
            <button class="edit-btn" @click="handleEdit(item)">编辑</button>
            <button class="delete-btn" @click="handleDelete(item.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>

    <!-- 添加/编辑对话框 -->
    <div v-if="dialogVisible" class="dialog-overlay">
      <div class="dialog">
        <h2>{{ dialogTitle }}</h2>
        <form @submit.prevent="submitForm">
          <div class="form-group">
            <label>家居名：</label>
            <input v-model="form.name" required />
          </div>
          <div class="form-group">
            <label>厂商：</label>
            <input v-model="form.maker" required />
          </div>
          <div class="form-group">
            <label>价格：</label>
            <input v-model.number="form.price" type="number" required />
          </div>
          <div class="form-group">
            <label>销量：</label>
            <input v-model.number="form.sales" type="number" />
          </div>
          <div class="form-group">
            <label>库存：</label>
            <input v-model.number="form.stock" type="number" />
          </div>
          <div class="dialog-buttons">
            <button type="button" @click="dialogVisible = false">取消</button>
            <button type="submit">确定</button>
          </div>
        </form>
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <div v-if="confirmVisible" class="dialog-overlay">
      <div class="dialog">
        <h2>确认删除</h2>
        <p>确定要删除这条记录吗？</p>
        <div class="dialog-buttons">
          <button @click="confirmDelete(true)">确定</button>
          <button @click="confirmDelete(false)">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { saveFurn, listFurn, deleteFurn, updateFurn } from "@/api/furn.js";

export default {
  data() {
    return {
      furnList: [],
      dialogVisible: false,
      confirmVisible: false,
      dialogTitle: '添加家居',
      isEditMode: false,
      deleteId: null,
      sortField: 'price',
      sortDirection: 'asc',
      form: {
        id: null,
        name: '',
        maker: '',
        price: 0,
        sales: 0,
        stock: 0
      }
    }
  },
  created() {
    this.fetchFurnList();
  },
   methods: {
    async fetchFurnList() {
      try {
        const res = await listFurn();
        
        // 关键修改：从res.data获取数组
        this.furnList = Array.isArray(res.data) ? res.data : [];
        
        console.log('当前列表数据:', this.furnList); // 调试用
      } catch (error) {
        console.error('获取数据失败:', error);
        alert('获取数据失败，请检查控制台');
      }
    },
    showDialog() {
      this.dialogTitle = '添加家居';
      this.isEditMode = false;
      this.resetForm();
      this.dialogVisible = true;
    },
    handleEdit(item) {
      this.dialogTitle = '编辑家居';
      this.isEditMode = true;
      this.form = { ...item };
      this.dialogVisible = true;
    },
    handleDelete(id) {
      this.deleteId = id;
      this.confirmVisible = true;
    },
    async confirmDelete(confirm) {
      this.confirmVisible = false;
      if (confirm) {
        try {
          await deleteFurn(this.deleteId);
          this.fetchFurnList();
          alert('删除成功');
        } catch (error) {
          alert('删除失败');
          console.error(error);
        }
      }
    },
async submitForm() {
  try {
    // 验证表单
    await this.$refs.formRef?.validate();
    
    if (this.isEditMode) {
      await updateFurn(this.form);  // 使用更新接口
      alert('更新成功');
    } else {
      await saveFurn(this.form);   // 使用添加接口
      alert('添加成功');
    }
    
    this.dialogVisible = false;
    this.fetchFurnList(); // 刷新列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error);
      alert('操作失败: ' + error.message);
    }
  }
},
    resetForm() {
      this.form = {
        id: null,
        name: '',
        maker: '',
        price: 0,
        sales: 0,
        stock: 0
      };
    },
    sortBy(field) {
      if (this.sortField === field) {
        this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
      } else {
        this.sortField = field;
        this.sortDirection = 'asc';
      }
      this.furnList.sort((a, b) => {
        const valA = a[field];
        const valB = b[field];
        return this.sortDirection === 'asc' ? valA - valB : valB - valA;
      });
    }
  }
};
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.add-btn {
  background: #409eff;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 4px;
  cursor: pointer;
  margin-bottom: 20px;
}

.add-btn:hover {
  background: #66b1ff;
}

.furn-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.furn-table th, .furn-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

.furn-table th {
  background-color: #f5f5f5;
  cursor: pointer;
}

.furn-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

.furn-table tr:hover {
  background-color: #f1f1f1;
}

.edit-btn, .delete-btn {
  padding: 5px 10px;
  margin-right: 5px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.edit-btn {
  background: #67c23a;
  color: white;
}

.delete-btn {
  background: #f56c6c;
  color: white;
}

.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.dialog {
  background: white;
  padding: 20px;
  border-radius: 5px;
  width: 400px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: inline-block;
  width: 80px;
}

.form-group input {
  padding: 8px;
  width: calc(100% - 90px);
  border: 1px solid #ddd;
  border-radius: 3px;
}

.dialog-buttons {
  text-align: right;
  margin-top: 20px;
}

.dialog-buttons button {
  padding: 8px 15px;
  margin-left: 10px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
}

.dialog-buttons button:first-child {
  background: #ddd;
}

.dialog-buttons button:last-child {
  background: #409eff;
  color: white;
}
</style>